//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using OpenLS.Spreadsheet.Expressions;

namespace OpenLS.Spreadsheet.Formats.Biff.Tokens
{
    internal class MemAreaToken : ComplexFormulaToken
    {
        private readonly AccessorType _type;

        public MemAreaToken(AccessorType type)
        {
            _type = type;
        }

        private ushort _size;

        public override ushort GetLength(FormulaReadContextType formulaReadContextType)
        {
            return 6;
        }


        internal override void ReadContent(FormulaReadContext context)
        {
            uint notUsed = context.ReadUInt32();
            _size = context.ReadUInt16();
        }
        public override void WriteContent(FormulaWriteContext context)
        {
            throw new NotImplementedException();
        }

        public override FormulaTokenId TokenId
        {
            get {
                switch (_type)
                {
                    case AccessorType.Array:
                        return FormulaTokenId.MemAreaA;
                        case AccessorType.Reference:
                        return FormulaTokenId.MemArea;
                        case AccessorType.Value:
                        return FormulaTokenId.MemAreaV;
                    default:
                        throw new NotSupportedException();
                } }
        }

        internal override Expression GetExpression(FormulaEvaluationContext context)
        {
            return context.PoppedArgument().GetExpression(context);
        }
        private readonly List<RangeAddress16> _addresses = new List<RangeAddress16>();
        public override void ReadAfter(BinaryReader reader)
        {
            ushort count = reader.ReadUInt16();
            for (ushort i = 0; i < count; i++)
            {
                _addresses.Add(new RangeAddress16 (reader));
            }
        }

        public override void WriteAfter(BinaryWriter writer)
        {
            ushort count = (ushort) _addresses.Count;
            writer.Write(count);
            foreach (var rangeAddress in _addresses)
            {
                rangeAddress.Write(writer);
                //\\AddressHelper.WriteRangeAddress16(rangeAddress, writer);
            }
        }
    }
}